<?php echo $html->script('jquery.colorbox-min.js?20120117', array('inline' => false));?>
<?php echo $html->script('student_classes.js?20120119', array('inline' => false));?>

<?php echo $html->css('colorbox.css?20120118', 'stylesheet', array('inline' => false));?>
<?php echo $html->css('student_classes.css?20120117', 'stylesheet', array('inline' => false));?>

<div class="<?=$this->params['controller']?> <?=$html->action?>">
    <?php echo $form->create('StudentClass');?>
	<fieldset>
 		<legend>Edit kelas</legend>
        <table class="input">
            <tr>
                <td class="label-required">Nama Prodi</td>
                <td>
                <?php 
                    echo $form->select('study_program_id', $study_programs, null, array(
                        'div'=>false, 'label'=>false, 'class'=>'required'
                        ), true);
                    echo ($form->isFieldError('study_program_id')) ? $form->error('study_program_id') : '';
                ?>
                </td>
            </tr>
            <tr>
                <td class="label-required">Nama kelas:</td>
                <td><?php echo $form->input('name', array('div'=>false, 'label' => false, 'maxlength' => 50, 'class'=>'required'));?></td>
            </tr>
            <tr>
                <td class="label-required">Tahun masuk:</td>
                <td>
                <?php
                    echo $form->input('year_started', array(
                        'div'=>false, 'label' => false, 'maxlength' => 4,
                        'class'=>'required year_started', 'type' => 'date',
                        'dateFormat' => 'Y', 'minYear' => $selectMinYear,
                        'maxYear' => $selectMaxYear,
                        'selected' => $this->data['StudentClass']['year_started'] .
                                      '-00-00',
                    ));
                ?>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <table id="students" class="students">
                        <thead>
                            <tr>
                                <th>&nbsp;</th>
                                <th>Nama mahasiswa</th>
                                <th>NIM</th>
                                <th>Jenis Kelamin</th>
                                <th>&nbsp;</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php if ( isset($students) && !empty($students) ): ?>
                        <?php
                            foreach ($students as $key => $student):
                                echo '<tr class="row_student" id="r'.$key.'" rel="r'.$key.'">';
                                    echo '<td>' .
                                         '<input type="checkbox" name="data[Student]['.$key.'][Student][id]" class="cb_student" class="inputText" value="' . $student['Student']['id'] . '" />' .
                                        '</td>';
                                    // nama
                                    echo '<td>';
                                    echo $form->input('name',
                                            array(
                                                'id' => null,
                                                'name' => 'data[Student]['.$key.'][Student][name]',
                                                'class' => 'inputText name',
                                                'div' => false, 'label' => false,
                                                'value' => $student['Student']['name']
                                            )
                                        );
                                    echo '</td>';
                                    // nim
                                    echo '<td>';
                                    echo $form->input('npm', array(
                                            'div' => false, 'label' => false,
                                            'id' => null, 'class' => 'inputText npm',
                                            'name' => 'data[Student]['.$key.'][Student][npm]',
                                            'value' => $student['Student']['npm']
                                        ));
                                    echo '</td>';
                                    // gender
                                    echo '<td>';
                                    echo $form->select('gender', array('M' => 'Laki-laki', 'P' => 'Perempuan'), $student['Student']['gender'], array(
                                            'id' => null, 'class' => 'gender',
                                            'name' => 'data[Student]['.$key.'][Student][gender]',
                                            'empty' => false
                                        ));
                                    echo '</td>';
                                    // edit detail and payment
                                    echo '<td>';
                                    echo $html->link('Detail Profil', array(
                                          'action' => 'student_payment', $student['Student']['id']
                                        ), array(
                                          'title' => 'Detail profil ' . $student['Student']['name'],
                                          'class' => 'colorbox'
                                    )) . ' | ';
                                    echo $html->link('Pembayaran', array(
                                        'action' => 'student_payment', $student['Student']['id']
                                        ), array(
                                          'title' => 'Pembayaran ' . $student['Student']['name'],
                                          'class' => 'colorbox'
                                    ));
                                    echo '</td>';
                                echo '</tr>';
                            endforeach;
                        ?>
                        <?php else: ?>
                            <tr class="row_student" id="r0" rel="r0">
                                <td>
                                    <input type="checkbox" name="data[Student][0][Student][id]" class="cb_student" class="inputText" />
                                </td>
                                <td>
                                    <?php
                                        // name
                                        echo $form->input('name',
                                            array(
                                                'id' => null,
                                                'name' => 'data[Student][0][Student][name]',
                                                'class' => 'inputText name',
                                                'div' => false, 'label' => false
                                            )
                                        );
                                    ?>
                                </td>
                                <td>
                                    <?php
                                        // npm
                                        echo $form->input('npm', array(
                                            'div' => false, 'label' => false,
                                            'id' => null, 'class' => 'inputText npm',
                                            'name' => 'data[Student][0][Student][npm]'
                                        ));
                                    ?>
                                </td>
                                <td> 
                                    <?php
                                        // gender
                                        echo $form->select(
                                        'gender', array('M' => 'Laki-laki', 'P' => 'Perempuan'), null,
                                        array(
                                            'id' => null,
                                            'class' => 'gender',
                                            'name' => 'data[Student][0][Student][gender]',
                                            'empty' => false
                                        ));
                                    ?>
                                </td>
                                <td></td>
                            </tr>
                        <?php endif;?>
                        </tbody>
                        <tfoot>
                            <tr>
                                <th>&nbsp;</th>
                                <th colspan="5">
                                    <span class="up"></span>
                                    <input type="button" name="add_row" id="add_row" value="+ Tambah Mahasiswa" /> &nbsp; atau &nbsp;
                                    <input type="button" name="del_row" id="real_del_row" value="- Hapus Mahasiswa" />
                                </th>
                            </tr>
                        </tfoot>
                    </table>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                <?php
                    echo $form->submit(__('Save', true), array('div'=>false)) . '&nbsp;' . __('or', true) . '&nbsp;';
                    echo $html->link(__('Delete', true), array('action'=>'delete', $this->data['StudentClass']['id']), array('class'=>'del'), sprintf(__('Are you sure you want to delete', true) . ' %s?', $this->data['StudentClass']['name'])) . "&nbsp;" . __('or', true) . "&nbsp;";
                    echo $html->link(__('Back to index', true), array('action'=>'index'));
                ?>
                </td>
            </tr>
        </table>
	</fieldset>
</form>
</div>

<script type="text/javascript">
$(function() {
    var tplInlineEdit = 
      '<div style="margin: 0; padding: 0;" id="inline-edit">'+
        '<a href="#" id="inline-edit-save" tabindex="-1">Save</a>' + ' &nbsp; '+
        '<a href="#" id="inline-edit-cancel" tabindex="-1">Cancel</a></div>';
    var inlineEditBackupValue;
    var inlineEditPostURL = '<?php echo $ajaxURL;?>inline_edit/';
    var deleteRowsURL = '<?php echo $ajaxURL;?>delete_students/';
    var succeedColor = '#B9DD96';
    var failedColor  = '#D38981';

    // colorbox
    $('.colorbox').colorbox({
         iframe: true,
         width: "918px",
         height: "440px"
    });

    // fadeOut from specified color to original color
    function animRow(row, color) {
      var rowOriBg = row.css('background-color');

      row.css({
        'background-color': color
      }).animate({
        opacity: 0.5,
      }, 500, function() {
        row.css({
          'background-color': rowOriBg,
          'opacity': 1
        })
      });
    }

    // save via inline edit
    function save(input) {
        var data  = {};

        // get id of current student
        var row = input.parent().parent();
        var id  = $('.cb_student', row).val();
        data['id'] = id;       
        data['name'] = $('.name', row).val();
        data['npm'] = $('.npm', row).val();
        data['gender'] = $('.gender', row).val();
        data['student_class_id'] = <?php echo $id;?>;

        $.post(inlineEditPostURL + id, data, function(ok) {
            if (ok) {
                animRow(input.parent().parent(), succeedColor);
            } else {
                animRow(input.parent().parent(), failedColor);
            }
        });

        // remove active inline-edit
        $('#inline-edit').remove();
    }

    // delete rows
    function deleteRows(rows) {
        var data = {};
        var total = 0;
        $.each(rows, function(idx, row) {
            if ( row.value.length ) {
                data['id[' + idx + ']'] = row.value;
                total++;
            }
            // remove the row
            var rowId = $(this).parent().parent().attr('id');
            $('tr[id^=' + rowId + ']').remove();
        });

        if (total) {
            $.post(deleteRowsURL, data);
        }
    }

    // cancel inline edit
    function cancel(input) {
        // restore the value from the backup
        input.val(inlineEditBackupValue);
        inlineEditBackupValue = '';

        // remove active inline-edit
        $('#inline-edit').remove();
    }

    $('#students').live('focusin', function(e) {
        var target = $(e.target);

        if ( target.hasClass('name') || target.hasClass('npm') ) {
          // remove active inline edit
          $('#inline-edit').remove();

          // backup value first
          inlineEditBackupValue = target.val();

          target.parent().append(tplInlineEdit);
        }

    }).live('focusout', function(e) {
        /*var target = $(e.target);
        if ( target.hasClass('name') || target.hasClass('npm') ) {
            cancel(target);
        }*/

    }).live('click', function(e) {
        var target = $(e.target);

        // ajax POST
        if ( target.attr('id') == 'inline-edit-save' ) {
            var input = target.parent().parent().children('.inputText');
            save(input);
        }

        // cancel inline edit
        if ( target.attr('id') == 'inline-edit-cancel' ) {
            cancel(target.parent().parent().children('.inputText'));
        }

        // checkbox
        if ( target.hasClass('cb_student') ) {
            return true;
        }

        e.preventDefault();
        return false;
    });

    $('.gender').live('change', function() {
        save($(this));
    });

    $('#real_del_row').click(function(e) {
        var totalCb = $('.cb_student').length;
        var totalChecked = $('.cb_student:checked').length;
        
        if ( totalChecked == 0 ) {
            alert('Centang mahasiswa yang ingin Anda hapus pada kotak\n'+
                  'kecil sebelah kiri nama mahasiswa'
            );
            return false;
        }
        
        if ( totalChecked < totalCb ) {
            deleteRows($('.cb_student:checked'));
        } else {
            alert('Anda tidak dapat mahasiswa ini,\n' +
                  'karena harus ada 1 mahasiswa yang tersisa, jika ada\n' +
                  'lebih dari 1 mahasiswa, maka mahasiswa ini dapat dihapus'
            );
            return false;
        }
        
        e.preventDefault();
    });
});
</script>
